from flask import Blueprint, render_template, request, session
import hashlib
from utils.database_util import query_data
user_center = Blueprint('user_center', __name__)
@user_center.route('/user_center')
def index4():
    return render_template("user_center.html")
@user_center.route('/login' , methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username');
        password = request.form.get('password');
        password = hashlib.md5(password.encode()).hexdigest()
        sql = "select * from users where username = '%s' and password = '%s'" % (username, password)
        result = query_data(sql)
        if len(result) == 0:
            return render_template("login.html")
        else:
            session['username'] = username
            session['islogin'] = 'true'
            session['userid'] = result[0].get('userid')
            session['nickname'] = result[0].get('nickname')
            session['role'] = result[0].get('role')
        return render_template("home.html")
    else:
        return render_template("login.html")

@user_center.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username');
        password = request.form.get('password');
        nickname = request.form.get('nickname');
        password = hashlib.md5(password.encode()).hexdigest()
        sql = "insert into users (username,password,nickname) values ('%s','%s','%s')" % (username, password, nickname)
        print(sql)
        result = query_data(sql)
        login()
        return render_template("home.html")

    else:
        return render_template("register.html")


@user_center.route('/logout', methods=['GET'])
def logout():
    # 清除会话中的用户信息
    session.pop('username', None)
    session.pop('islogin', None)
    session.pop('userid', None)
    session.pop('nickname', None)
    session.pop('role', None)
    # 重定向到登录页面
    return render_template('home.html')


@user_center.route('/my_favorite')
def my_favorite():
    return render_template('my_favorite.html')

@user_center.route('/my_drafts')
def my_drafts():
    return render_template('my_drafts.html')

@user_center.route('/my_articles')
def my_articles():
    return render_template('my_articles.html')

@user_center.route('/my_comments')
def my_comments():
    return render_template('my_comments.html')

@user_center.route('/personal_info')
def personal_info():
    return render_template('personal_info.html')

@user_center.route('/my_points')
def my_points():
    return render_template('my_points.html')
